package com.example.Service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.Dao.UserMapper;
import com.example.Entity.Dto.UserInfo;
import com.example.Entity.Po.tn_sys_user;
import com.example.Entity.Vo.APIResult;
import com.example.Entity.Vo.loginVo;
import com.example.IService.IUserService;
import com.example.Utils.EncryptionUtils;
import com.example.Utils.JsonUtils;
import com.example.Utils.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserService extends BaseService implements IUserService {
    @Resource
    UserMapper userMapper;

    /**
     * 用户登录
     * @param loginVo 实体
     * @return APIResult
     */
    @Override
    public APIResult Login(loginVo loginVo) {
        if(loginVo==null)
            return APIResult.error("请填写信息");
        if (StringUtils.isBlank(loginVo.getUseraccount()))
            return APIResult.error("请填写账号");
        if (StringUtils.isBlank(loginVo.getPassword()))
            return APIResult.error("请填写密码");
        String newpassword = EncryptionUtils.getPWD(loginVo.getPassword());
        QueryWrapper<tn_sys_user> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",loginVo.getUseraccount());
        queryWrapper.eq("password", newpassword);
        tn_sys_user user = userMapper.selectOne(queryWrapper);
        if (user==null)
            return APIResult.error("不存在该用户，请检查账号或者密码是否正确");
        StpUtil.login(user.getUserid());
        String token = StpUtil.getTokenValue();
        if (token==null)
            return APIResult.error("登录失败");
        // 用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getUserid());
        userInfo.setUsername(user.getUsername());
        userInfo.setEmail(user.getEmail());
        userInfo.setPath(user.getUserpath());
        userInfo.setCreatetime(user.getCreatetime());
        userInfo.setRecommend(user.getRecommend());
        userInfo.setJurisdiction(user.getJurisdiction());
        userInfo.setToken(token);
        boolean b = SetSessionInfo(userInfo);
        if (!b)
            return APIResult.error("登录失败");
        return APIResult.success("登录成功",userInfo);
    }

    /**
     * 检测用户是否登录
     * @return APIResult
     */
    @Override
    public APIResult CheckLogin() {
        UserInfo u = GetSessionInfo();
        boolean b = StpUtil.isLogin();
        if (b)
            return APIResult.success();
        else
            return APIResult.error("请重新登录",1001);
    }
}
